<template>
  <div id="userLayout" class="user-layout-wrapper">
    <div class="container">
      <el-container>
        <div class="login-top-bg"></div>
      </el-container>
    </div>

    <div class="login-main">
      <div class="login-title">
        <span>内蒙应急指挥系统信息维护系统</span>
      </div>
      <el-card>
        <div class="login-content">
          <div class="login-img">
            <img src="@/assets/loginFormBigImg.png" width="100%" />
          </div>
          <div class="login-form-div">
            <div class="form-title">
              <span>欢迎登录</span>
            </div>
            <el-form
                class="login-form"
                :model="loginForm"
                :rules="rules"
                ref="loginForm"
            >
              <el-form-item prop="mobile">
                <el-input
                    placeholder="请输入手机号码" 
                    maxlength="11"
                    v-model="loginForm.mobile"
                    prefix-icon="el-icon-user"
                    clearable
                    @keyup.enter.native="
                    loginEvent(loginForm.code, loginForm.mobile)
                  "
                />
              </el-form-item>
              <!--              <el-form-item style="position: relative">-->
              <!--                <el-input-->
              <!--                  class="enter-code"-->
              <!--                  v-model="loginForm.captcha"-->
              <!--                  name="logVerify"-->
              <!--                  placeholder="请输入图形验证码"-->
              <!--                  maxlength="6"-->
              <!--                  style="width: 60%"-->
              <!--                  prefix-icon="el-icon-key"-->
              <!--                  clearable-->
              <!--                />-->
              <!--                <div class="vPic">-->
              <!--                  <img-->
              <!--                    v-if="picPath"-->
              <!--                    :src="picPath"-->
              <!--                    width="100%"-->
              <!--                    height="100%"-->
              <!--                    alt="请输入验证码"-->
              <!--                    @click="loginVefify()"-->
              <!--                  />-->
              <!--                </div>-->
              <!--              </el-form-item>-->
              <el-form-item style="position: relative">
                <el-input
                    class="enter-code"
                    v-model="loginForm.code"
                    name="logVerify"
                    placeholder="请输入短信验证码" 
                    prefix-icon="el-icon-key"
                    clearable
                    type="password"
                    @keyup.enter.native="
                    loginEvent(loginForm.code, loginForm.mobile)
                  "
                />
                <!-- <div class="phone-code">
                  <el-button
                      slot="append"
                      type="primary"
                      :loading="loading"
                      @click="
                      sendPhoneCode(
                        loginForm.mobile,
                        loginForm.captchaID,
                        loginForm.captcha
                      )
                    "
                  >{{ !loading ? "发送验证码" : `${cd}s 后再试` }}</el-button
                  >
                </div> -->
              </el-form-item>
              <el-form-item>
                <el-button
                    class="login-submit"
                    type="primary"
                    :loading="loginLoading"
                    @click="loginEvent(loginForm.code, loginForm.mobile)"
                    @keyup.enter.native="
                    loginEvent(loginForm.code, loginForm.mobile)
                  "
                >登 录</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import Base64 from "base-64";
import { mapActions } from "vuex";
import { captcha, getPhoneCode } from "@/api/user";
// 引入表单验证插件
import form from "@/utils/formValidation";
import  store   from "@/store/index.js";
import  {getUserRouter, resetRouter}   from "@/router/index.js"; 
export default {
  name: "Login",
  data() {
    const checkPhoneNumber = (rule, value, callback) => {
      if (form._isNullOrEmpty(value)) {
        return callback(new Error("请输入手机号"));
      } else if (value.length !== 11) {
        return callback(new Error("手机号长度需为11位"));
      } else if (!form._isMobile(value)) {
        return callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      loginLoading: false,
      loading: false,
      cd: 60,
      loginForm: {
        mobile: "13800000000",
        captcha: "",
        captchaID: "",
        code: "nmgyjt@123456",
      },
      rules: {
        mobile: [{ validator: checkPhoneNumber, trigger: "blur" }],
      },
      logVerify: "",
      picPath: "",
    };
  },
  created() {
    // this.loginVefify();
    console.log("当前时间：", new Date().getTime());
    let nowDate = new Date(new Date().getTime() + 1000 * 60);
    console.log("nowDate:", nowDate);
  },
  methods: {
    ...mapActions("user", ["LoginIn"]),
    // 调用登录接口
    loginEvent(code, mobile) {
      this.$refs["loginForm"].validate(async (valid) => {
        // 手机号码校验通过
        if (!valid) return false;
        // 已输入验证码
        // if (!this.loginForm.captcha || !this.loginForm.code) {
        //   this.$message({ type: "error", message: "请输入验证码" });
        //   return false;
        // }
        this.loginLoading = true;
 
       
        // store.commit("user/setUserInfo", res.body) 
        let data={
          body:{
            phone: mobile,
            password: code
          }
        }
        this.$api.AdminController.login(data, null, this.$error).then(res=>{         
          console.log(res);       
          let body=res.data
          // body.menuPermission=""
          let userRouters=getUserRouter(body?body.menuPermission:"", body) 
          store.commit('SET_ROUTERS', userRouters);
          store.commit("user/setUserInfo", body);
          store.commit("user/setToken", Base64.encode(body.phone));
          resetRouter() 
          let menu =userRouters[0].children[0]
          this.link(menu.name, menu.meta.query) 
        })
      }) 
    },

    // 调用图形验证码接口
    // async loginVefify() {
    //   await captcha({}).then((ele) => {
    //     this.loginForm.captcha = "";
    //     this.picPath = ele.data.image;
    //     this.loginForm.captchaID = ele.data.captchaID;
    //   });
    // },

    // 调用短信验证码接口
    async sendPhoneCode(mobile, captchaID, captcha) {
      this.$refs["loginForm"].validate(async (valid) => {
        // 手机号码校验是否合法
        if (!valid) {
          return false;
        }

        // 图形验证码校验是否合法
        // if (this.loginForm.captcha.length !== 6) {
        //   this.$message({ type: "error", message: "请输入正确的图形验证码" });
        //   return false;
        // }

        await getPhoneCode({
          sms: {
            mobile,
          },
          captchaID,
          code: captcha,
        })
            .then((res) => {
              if (res.code === 0) {
                this.$message({ type: "success", message: "已发送短信验证码" });
                // 事件完成后将按钮加载状态流转为false并设置CD为60s
                // 需将此处CD存储在本地，防止用户刷新页面后CD重置为0
                let timer = setInterval(() => {
                  if (this.cd) {
                    this.cd = this.cd - 1;
                    this.loading = true;
                  } else {
                    this.loading = false;
                    this.cd = 60;
                    clearInterval(timer);
                  }
                }, 1000);
              }
            })
            .catch((err) => {
              // this.loginVefify();
              console.log("err:", err);
            });
      });
    },
  },
};
</script>

<style lang="scss">
@import "./login.scss";
</style>
